
package net.badcurrent.ldapodm.ldap;

import org.springframework.ldap.AttributesMapper;
import org.springframework.ldap.support.DistinguishedName;

import javax.naming.directory.Attributes;
import javax.naming.directory.Attribute;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import java.util.List;
import java.util.ArrayList;

/**
 * <code>AttributesMapper</code> to map LDAP attributes to a <code>Collection</code>/
 */
public class CollectionAttributesMapper implements AttributesMapper {
    private String memberName;
    private String baseDn;

    public CollectionAttributesMapper(String memberName, String baseDn) {
        this.memberName = memberName;
        this.baseDn = baseDn;
    }

    public Object mapFromAttributes(Attributes attributes) throws NamingException {
        Attribute attr = attributes.get(memberName);
        NamingEnumeration namingEnumeration = attr.getAll();
        List<DistinguishedName> members = new ArrayList<DistinguishedName>();
        while (namingEnumeration.hasMore()) {
            String dn = namingEnumeration.next().toString();
            if (dn.endsWith("," + baseDn)) {
                members.add(new DistinguishedName(dn.split("," + baseDn)[0]));
            } else {
                members.add(new DistinguishedName(dn));
            }
        }
        return members;
    }
}
